﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using MeetCommon.MveServiceReference;

namespace MeetCommon.Service
{
	/*
	 * 日本SGI株式会社
	 * ヨハンソン・ヘンリク
	 * johansson@sgi.co.jp
	 * 
	 * Comments:
	 *		Replaces the original MeetServerConnector.cs
	 * 
	 * Change Log:
	 * ---------------------------------------------------------------------------
	 * 2009.01.19	Johansson Henrik		Class Created.
	 * 2009.01.20							Added string resource loading and error handling.
	 *										Added Service Reference.
	 *										Added Service Calling Code.
	 * 2009.01.22							Added the line 'result.LoadXml(response);' to
	 *										QuerySegmentByKeyword.
	 */

	/// <summary>
	/// Handles all connections to The MvePublicService, Video Explorer Server.
	/// </summary>
	/// <remarks>INSERT:CREDS</remarks>
	public class MeetServerConnector
	{
		/// <summary>
		/// Holds the User Id used in communications with the
		/// Server. This Id is aquired when the user logs in
		/// to the Server.
		/// </summary>
		private Guid _currentUserServiceId = Guid.Empty;

		/// <summary>
		/// Logon (verify) the user credentials with the Server.
		/// If logon is successful, this method will set the private
		/// User Service Id member to a Guid stored on the Server.
		/// This Guid is valid only for this session.
		/// </summary>
		/// <param name="logonId">Username</param>
		/// <param name="password">Password</param>
		/// <returns>True if the operation was successful</returns>
		public bool Logon(string logonId, string password)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				this._currentUserServiceId = client.LogOn(logonId, password);
				client.Close();

				if (this._currentUserServiceId != Guid.Empty)
					result = true;

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_LogonFailed,
					Properties.Resources.MsgT_LogonFailed, ex);
			}
		}//end:Logon

		/// <summary>
		/// This method was never called in the original MeetServerConnector.cs,
		/// thus it is not implemented here.
		/// </summary>
		public XmlDocument QueryClips()
		{
			throw GetNetworkOperationException(
				Properties.Resources.Msg_OperationNotImplOnServer,
				Properties.Resources.MsgT_OperationFailed, null);
		}//end:QueryClips

		/// <summary>
		/// This method was never called in the original MeetServerConnector.cs,
		/// thus it is not implemented here.
		/// </summary>
		public XmlDocument ClipSegments(int clip_id)
		{
			throw GetNetworkOperationException(
				Properties.Resources.Msg_OperationNotImplOnServer,
				Properties.Resources.MsgT_OperationFailed, null);
		}//end:ClipSegments

		/// <summary>
		/// Gets a single clip, with segment and keyword data,
		/// out of the the Database.
		/// </summary>
		/// <param name="clipId">Id of the clip to retrieve.</param>
		/// <returns>An XML representation of the Clip.</returns>
		public XmlDocument Clip(int clipId)
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.Clip(this._currentUserServiceId, clipId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetClipFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:clip

		/// <summary>
		/// Given a Segment Id, get data for the Clip that the 
		/// Segment belongs to.
		/// </summary>
		/// <param name="segmentId">Id of the Segment for which to get Clip data.</param>
		/// <returns>An XML representation of the Clip data.</returns>
		public XmlDocument ClipBySegmentId(int segmentId)
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.ClipBySegmentId(this._currentUserServiceId, segmentId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetClipBySegmentIdFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:ClipBySegmentId

		/// <summary>
		/// Searches the database for all Segments tagged with the given Keyword.
		/// </summary>
		/// <param name="keyword">The Keyword to search for.</param>
		/// <returns>An XML representation of all the Segments tagged with the given Keyword, including their Clip data.</returns>
		public XmlDocument QuerySegmentByKeyword(string keyword)
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.QuerySegmentByKeyword(this._currentUserServiceId, keyword);
				client.Close();

				result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_SearchSegmentByKeywordFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:QuerySegmentByKeyword

		/// <summary>
		/// Get all the user's Keywords.
		/// </summary>
		/// <returns>An XML representation of all the Keywords.</returns>
		public XmlDocument QueryKeywords()
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.QueryKeywords(this._currentUserServiceId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetKeywordsFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:QueryKeywords

		/// <summary>
		/// Adds a Keyword and Segment pair to the Keyword database.
		/// </summary>
		/// <param name="segmentId">Id of the Segment to pair with this Keyword.</param>
		/// <param name="keyword">The Keyword to add.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool AddKeywordToSegment(int segmentId, string keyword)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.AddKeywordToSegment(this._currentUserServiceId, segmentId, keyword);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_AddSegmentKeywordFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:AddKeywordToSegment

		/// <summary>
		/// Deletes a Keyword / Segment pair.
		/// </summary>
		/// <param name="keywordId">Id of the Keyword to delete.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool DeleteKeyword(int keywordId)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.DeleteKeyword(this._currentUserServiceId, keywordId);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_DeleteKeywordFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:DeleteKeyword

		/// <summary>
		/// Adds a Keyword to the User's Idea Basket.
		/// </summary>
		/// <param name="keyword">The Keyword to add.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool AddKeywordToIdeaBasket(string keyword)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.AddKeywordToIdeaBasket(this._currentUserServiceId, keyword);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_AddBasketKeywordFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:AddKeywordToIdeaBasket

		/// <summary>
		/// Deletes a Keyword from the User's Idea Basket.
		/// </summary>
		/// <param name="keyword">The Keyword to delete.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool DeleteIdeaBasketKeyword(string keyword)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.DeleteIdeaBasketKeyword(this._currentUserServiceId, keyword);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_DeleteBasketKeywordFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:DeleteIdeaBasketKeyword

		/// <summary>
		/// Get all the User's Bookmarks.
		/// </summary>
		/// <returns>An XML representation of the User's Bookmarks.</returns>
		public XmlDocument QueryBookmarks()
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.QueryBookmarks(this._currentUserServiceId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetBookmarksFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:QueryBookmarks

		/// <summary>
		/// Add a bookmark for the current User, to the given Segment Id.
		/// </summary>
		/// <param name="segmentId">Id of the Segment to Bookmark.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool AddBookmark(int segmentId)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.AddBookmark(this._currentUserServiceId, segmentId);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_AddBookmarkFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:AddBookmark

		/// <summary>
		/// Delete the Bookmark for the given Segment Id.
		/// </summary>
		/// <param name="segmentId">Id of the Segment for which to delete the Bookmark.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool DeleteBookmark(int segmentId)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.DeleteBookmark(this._currentUserServiceId, segmentId);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_DeleteBookmarkFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:DeleteBookmark

		/// <summary>
		/// Get all Relations for the given Segment Id from the database.
		/// </summary>
		/// <param name="segmentId">Id of the Segment for which to get all Relations.</param>
		/// <returns>An XML representation of all the relations.</returns>
		public XmlDocument GetRelations(int segmentId)
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.GetRelations(this._currentUserServiceId, segmentId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetRelationsFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:GetRelations

		/// <summary>
		/// Given a Segment Id, get all other related Segments.
		/// </summary>
		/// <param name="segmentId">Id of the parent Segment.</param>
		/// <returns>An XML representation of all the related Segments.</returns>
		public XmlDocument RelatedSegments(int segmentId)
		{
			try
			{
				XmlDocument result = new XmlDocument();
				string response = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				response = client.RelatedSegments(this._currentUserServiceId, segmentId);
				client.Close();

				if (string.IsNullOrEmpty(response))
					throw new ArgumentNullException(
						Properties.Resources.Msg_ServerReturnedInvalidResponse);
				else
					result.LoadXml(response);

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_GetRelatedSegmentsFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:RelatedSegments

		/// <summary>
		/// Save a string representation of the Xaml that makes up a Map.
		/// </summary>
		/// <param name="map">A string representation of a Map.</param>
		/// <returns>True if the operation was successful.</returns>
		public bool SaveMap(string map)
		{
			try
			{
				bool result = false;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.SaveMap(this._currentUserServiceId, map);
				client.Close();

				return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_SaveMapFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:SaveMap

		/// <summary>
		/// Load the saved Map matched to the current User Service Id.
		/// </summary>
		/// <returns>A string representation of a Map.</returns>
		public string LoadMap()
		{
			try
			{
				string result = string.Empty;

				MvePublicServiceClient client = new MvePublicServiceClient();
				result = client.LoadMap(this._currentUserServiceId);
				client.Close();

                if (string.IsNullOrEmpty(result))
                {
                    // let's take a empty map
                    return string.Empty;
                    //throw new ArgumentNullException(
                    //    Properties.Resources.Msg_ServerReturnedNullMap);
                }
                else
                    return result;
			}
			catch (Exception ex)
			{
				throw GetNetworkOperationException(
					Properties.Resources.Msg_LoadMapFailed,
					Properties.Resources.MsgT_OperationFailed,
					ex);
			}
		}//end:LoadMap

		/// <summary>
		/// Returnes a formatted Exception to pass back
		/// to any callers.
		/// </summary>
		/// <param name="Message">Message part of the Exception.</param>
		/// <param name="Title">Title part of the Exception.</param>
		/// <param name="InnerException">Original exception.</param>
		/// <returns>A formatted, initialized excpetion.</returns>
		private Exception GetNetworkOperationException(
			string Message, string Title, Exception InnerException)
		{
			MVENetworkOperationException exc =
				new MVENetworkOperationException(Title + "\n\n" + Message,
					InnerException);

			return exc;
		}//end:GetNetworkOperationException

	}
}
